package com.xszx.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xszx.config.PageRequest;
import com.xszx.dao.GoodsDao;
import com.xszx.dao.WarehouseDao;
import com.xszx.entity.Position;
import com.xszx.entity.Type;
import com.xszx.entity.Warehouse;
import com.xszx.entity.WarehouseRegionInfo;
import com.xszx.entity.*;
import com.xszx.utils.WarehouseCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WarehouseService {

    @Autowired
    private WarehouseDao warehouseDao;

    public PageInfo<Warehouse> WarehouseList(PageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getSize());
        List<Warehouse> WarehouseList = warehouseDao.WarehouseList(pageRequest);
        System.out.println(WarehouseList);
        return new PageInfo<>(WarehouseList);
    }

    public boolean delWarehouseByNumber(String number) {
        int ret = warehouseDao.delWarehouseByNumber(number);
        boolean flag = true;
        if(ret==0){
            flag = false;
        }
        return flag;
    }


    //获取仓库详细信息(根据仓库编号)
    public List<WarehouseRegionInfo> GetWarehouseRegionInfoByNumber(String number) {
        return warehouseDao.GetWarehouseInfoByNumber(number);
    }

    public boolean addWarehouse(Warehouse warehouse) {
        warehouse.setNumber(WarehouseCodeGenerator.generateWarehouseCode(warehouse.getType()));
        String tid= warehouseDao.getWarehousseTypeIdByTypeName(warehouse.getType());
        warehouse.setType(tid);
        return (warehouseDao.addWarehouse(warehouse)==1?true:false);
    }

    public List<Type> getWarehouseType() {
        return warehouseDao.getWarehouseType();
    }

    public Warehouse getWarehouseByNumber(String number) {
        Warehouse warehouse = warehouseDao.getWarehouseByNumber(number);
        return warehouse;
    }

    public List<Type> getRegionType() {
        return warehouseDao.getRegionType();
    }

    public boolean addRegionByWarehouseNumber(WarehouseRegionInfo warehouseRegionInfo) {
        //根据所属仓库名获得仓库的id
        warehouseRegionInfo.setWid(warehouseDao.getWidByWname(warehouseRegionInfo.getWname()));
        //根据仓库id去获取仓库编号
        warehouseRegionInfo.setWcode(warehouseDao.getWarehouseByWid(warehouseRegionInfo.getWid()));
        //根据type_name='3'去获取对应的区域类型名
        String typeName = warehouseDao.getRtypeName(warehouseRegionInfo.getType_name());
        System.out.println(typeName);
        warehouseRegionInfo.setR_code(WarehouseCodeGenerator.generateAreaCode(warehouseRegionInfo.getWcode(),typeName));
        //默认区域的可用面积和使用面积是一样的
        warehouseRegionInfo.setR_ableuse(warehouseRegionInfo.getA_area());
        int ret = warehouseDao.addRegionByWarehouseNumber(warehouseRegionInfo);
        Boolean flag = ret==0?false:true;
        return flag;
    }

    //修改 区域
    public void updateRegion(WarehouseRegionInfo warehouseRegionInfo) {
        //默认区域的可用面积和使用面积是一样的
        warehouseRegionInfo.setR_ableuse(warehouseRegionInfo.getA_area());
        //根据所属仓库名获得仓库的id
        warehouseRegionInfo.setWid(warehouseDao.getWidByWname(warehouseRegionInfo.getWname()));
        System.out.println(warehouseRegionInfo.getWid());
        //根据仓库id去获取仓库编号
        warehouseRegionInfo.setWcode(warehouseDao.getWarehouseByWid(warehouseRegionInfo.getWid()));
        //去查修改前的区域之前对应的区域类型名
        String typeName1 = warehouseDao.getRtypeN(warehouseRegionInfo.getWid(),warehouseRegionInfo.getRid());
        //查现在区域类型名
        String typeName = warehouseDao.getRtypeName(warehouseRegionInfo.getType_name());
        if(typeName.equals(typeName1)){
            System.out.println("区域类型名相同");
            warehouseDao.updateRegion(warehouseRegionInfo);
        }else {
            warehouseRegionInfo.setR_code(WarehouseCodeGenerator.generateAreaCode(warehouseRegionInfo.getWcode(),typeName));
            warehouseDao.updateRegion1(warehouseRegionInfo);
        }

    }

    //删除区域（必须区域内没有放置东西，才能删除）
    public boolean delRegion(Integer rid) {
        //如果是已出库才能删除,没有查到数据也可以删除
        List<Goods> goodsList = warehouseDao.IsDelRegionByNumber(rid);
        // 如果没有货物，直接删除区域
        if (goodsList == null || goodsList.isEmpty()) {
            warehouseDao.delRegionByNumber(rid);
            return true;
        }

        // 检查是否所有货物都已出库
        boolean canDelete = true;
        for (Goods goods : goodsList) {
            if (!"已出库".equals(goods.getState())) {
                System.out.println("有货物");
                canDelete = false;
                break;
            }
        }

        if (canDelete) {
            warehouseDao.delRegionByNumber(rid);
            return true;
        }

        return false;
    }

    //根据货物的类型获得能存放的仓库
    public List<Warehouse> getWarehousesByType(String gtype) {
        return warehouseDao.getWarehousesByType(gtype);
    }

    //根据wid获取仓库的区域信息
    public List<WarehouseRegionInfo> getRegionByWid(String wid) {
        return warehouseDao.getRegionByWid(wid);
    }
    //根据区域id获取区域类型信息

    public void updateWarehouse(Warehouse warehouse) {
        //通过仓库类型名去获取对应的类型id
        String tid= warehouseDao.getWarehousseTypeIdByTypeName(warehouse.getType());
        Warehouse warehouse1 = warehouseDao.getWarehouseByNumber(warehouse.getNumber());
        if(warehouse1.getType() != tid){
            warehouse.setNumber(WarehouseCodeGenerator.generateWarehouseCode(warehouse.getType()));
            warehouse.setType(tid);
        }
        System.out.println(warehouse);
        warehouseDao.updateWarehouse(warehouse);
    }

//    计算仓库使用率
    public double getWarehousearea(){
        MonthCount monthCount = warehouseDao.getWarehousearea();
        int areas = monthCount.getAreas();   // 单个/单层面积
        int nums = monthCount.getNums();   //货物使用了的面积
        if (areas == 0) {
            System.out.println("错误：仓库总面积为0，无法计算！");
            return 0;
        }
        double ratio1 = (double) nums / areas;
        System.out.println("货物使用了的比率为：" + ratio1);
        return ratio1;
    }
    //    获取仓位列表
    public List<Position> getpositionList(Integer rId) {
        return warehouseDao.getpositionList(rId);
    }

//    增加仓位
    public void addPosition(Position position) {
        warehouseDao.addPosition(position);
    }

//    修改仓位
    public void updatePosition(Position position) {
        warehouseDao.updatePosition(position);
    }

//    删除仓位
    public void deletePosition(Integer id) {
        warehouseDao.deletePosition(id);
    }

    public double getWarehouseGrend() {
        double growthRate = 0;
        // 从数据库获取按月统计结果// 按年月统计货物使用面积
        List<MonthCount> monthCounts = warehouseDao.countByYearMonth();
        MonthCount monthCount = warehouseDao.getWarehousearea();
        // 转换为Map // 存储每月货物使用面积
        Map<String, Integer> monthlyCounts = new HashMap<>();
        for (MonthCount mc : monthCounts) {
            monthlyCounts.put(mc.getYearMonth(), mc.getNums());
        }
        // 按月排序并计算环比
        List<String> sortedMonths = new ArrayList<>(monthlyCounts.keySet());
        Collections.sort(sortedMonths);
        for (int i = 1; i < sortedMonths.size(); i++) {
            String currentMonth = sortedMonths.get(i);
            String prevMonth = sortedMonths.get(i - 1);
            int currentCount = monthlyCounts.get(currentMonth);
            int prevCount = monthlyCounts.get(prevMonth);
            int areas = monthCount.getAreas();   //单层/总面积
            System.out.println("单层面积"+areas);
            if (areas == 0) {
                System.out.println("错误：仓库总面积为0，无法计算！");
                return 0;
            }
            growthRate = ((double) currentCount / prevCount - 1)*100;
            System.out.printf("%s月 vs %s月: 面积 %d vs %d, 环比增长: %.2f%%%n",
                    currentMonth, prevMonth, currentCount, prevCount, growthRate);
        }
        return growthRate;
    }


}
